<template>
  <div class="ant-message-container">
    <message-item
      v-for="item of instances"
      :key="item.messageId"
      :id=item.messageId
      :message=item
      @remove="handleRemove" />
  </div>
</template>
<script lang="ts">
import {defineComponent, ref} from 'vue';
import MessageItem from './MessageItem.vue';
import './index.scss';
import {MessageItemData} from "./index";
import mitt from 'mitt';

export default defineComponent({
  name: 'Message',
  components: { MessageItem },
  setup() {
    const instances = ref<MessageItemData[]>([]);
    const emitter = mitt();
    const createMessage = (item: MessageItemData) => {
      instances.value.push(item);
      // console.log('createMessage', instances.value);
    }

    const handleRemove = (id: string) => {
      // console.log('handleRemove', id);
      const index = instances.value.findIndex(item => item.messageId === id);
      if (index > -1) {
        const removeTarget = instances.value.splice(index, 1)[0];
        removeTarget?.onClose!.emit<string>('close', removeTarget.messageId);
        removeTarget?.onClose!.all.clear();
      }
      if (!instances.value.length) {
        emitter.emit('clear');
      }
    }

    // useExpose({ createMessage, emitter }); // 相当于将方法写在methods里
    // watch(
    //     () => instances,
    //     newVal => {
    //       // console.log(newVal.value.length);
    //       if (!newVal.value.length) {
    //         emitter.emit('clear');
    //       }
    //     },
    //     { deep: true } // vue3更新，改变数组成员无法watch
    // );
    return {
      createMessage,
      emitter,
      handleRemove,
      instances
    }
  }
});

</script>
<style lang="scss" src="./index.scss"></style>
